﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ZK.Common;
using System.Threading;
using System.Timers;
using ZK.InterfaceServer;
using ZK.HardWareBLL;
using Microsoft.VisualBasic;

namespace ZK.YHP_TransManage.UC
{
    public partial class Silo : UserControl
    {

        private static readonly object obj = new object();
        public CameraBLL cameraQ;
        public CameraBLL cameraG;
        public HardWareBLL.Onbon6K1CardBLL onbon6K1CardBLL;
        private HardWareBLL.YRTReaderBLL yRTReaderBLL;
        HardWareBLL.DLZCBLL dLZCBLL;
        public string cardNumNow = string.Empty;
        System.Timers.Timer rePeatCardNumTimer =
            new System.Timers.Timer(Convert.ToInt32(AppConfigHelper.GetAppSettings("RePeatCardNumTime")));
        System.Timers.Timer ShowDWTimer =
            new System.Timers.Timer(Convert.ToInt32(AppConfigHelper.GetAppSettings("ShowDWTimer")));
        bool dLZCRunState;
        ToledoWagonBalanceTCBLL toledoWagonBalanceBLL;
        public double nowWeight;
        string siloCoalName;
        int FJDW = Convert.ToInt32(AppConfigHelper.GetAppSettings("FJDW"));
        /// <summary>
        /// 清空并关闭授权的吨位限制
        /// </summary>
        double weightBZ;
        bool ShowDW;

        /// <summary>
        /// 运销车辆信息
        /// </summary>
        private Models.GetTruckYxInfoRceiveM yxYsTransportReturnDto;
        int clearTextTime;
        bool poundHasData;
        private WFAutoSizeHelper wFAutoSizeHelper = new WFAutoSizeHelper();
        bool dlzcState;
        /// <summary>
        /// 构造函数
        /// </summary>
        public Silo()
        {
            InitializeComponent();
            wFAutoSizeHelper.GetAllInitInfo(this.Controls[0], this);
        }

        /// <summary>
        /// 初始化led
        /// </summary>
        private void InitLed()
        {
            onbon6K1CardBLL = new HardWareBLL.Onbon6K1CardBLL();
            LedPageShow(Com.TipsStringHelper.Hyy);
        }

        /// <summary>
        /// led显示消息
        /// </summary>
        /// <param name="str"></param>
        private void LedShow(string str)
        {
            onbon6K1CardBLL.SCREEN_SendDynamicArea(str);
        }

        /// <summary>
        /// 提示信息现在在led，页面上。
        /// </summary>
        /// <param name="str"></param>
        private void LedPageShow(string str)
        {
            LedShow(str);
            PageShow(str);
        }

        /// <summary>
        /// 提示信息的最大长度
        /// </summary>
        private int InfoMaxLength = Convert.ToInt32(Common.AppConfigHelper.GetAppSettings("InfoMaxLength"));
        /// <summary>
        /// 在显示在页面中的提示信息的长度超过的个数，截取的比例
        /// </summary>
        private int InfoMaxLengthCut = Convert.ToInt32(Common.AppConfigHelper.GetAppSettings("InfoMaxLengthCut"));

        /// <summary>
        /// 提示信息显示在页面上
        /// </summary>
        /// <param name="str"></param>
        private void PageShow(string str)
        {

            this.Invoke(new Action(() =>
            {
                // textBoxInfo.tex
                int leg = textBoxInfo.TextLength;
                string infoTest = textBoxInfo.Text;
                if (leg > InfoMaxLength)
                {
                    infoTest = infoTest.Substring(leg / InfoMaxLengthCut);
                    textBoxInfo.Text = infoTest;
                }
                textBoxInfo.AppendText("--" + str + "\n");
            }));

            

        }

        int InOutClearTextTime = Convert.ToInt32(Common.AppConfigHelper.GetAppSettings("InOutClearTextTime"));


        /// <summary>
        /// 设置页面数据
        /// </summary>
        private void SetText()
        {
            try
            {
                if (string.IsNullOrWhiteSpace(yxYsTransportReturnDto.cardNo))
                {
                    return;
                }
                this.Invoke(new Action(() =>
                {
                    textBoxKZT.Text = Enum.GetName(typeof(SysDefinitionEnum.SendType), yxYsTransportReturnDto.sendType);
                    textBoxCYS.Text = yxYsTransportReturnDto.carrierName;
                    textBoxGSMC.Text = yxYsTransportReturnDto.shipperName;
                    textBoxHWMC.Text = yxYsTransportReturnDto.coalName;
                    textBoxBZ.Text = yxYsTransportReturnDto.memo;
                    textBoxLX.Text = Enum.GetName(typeof(SysDefinitionEnum.YxState), yxYsTransportReturnDto.yxState);
                }));
            }
            catch (Exception ex)
            {

                Common.Log4.LogManage.WriteErr(ex.ToString());
            }
        }

        /// <summary>
        /// 清空页面数据
        /// </summary>
        private void ClearText()
        {
            //Task.Factory.StartNew(() =>
            //{
            //Thread.Sleep(clearTextTime);
            this.Invoke(new Action(() =>
            {
                textBoxKZT.Text = "";
                textBoxCYS.Text = "";
                textBoxGSMC.Text = "";
                textBoxHWMC.Text = "";
                textBoxBZ.Text = "";
                textBoxLX.Text = "";
                textBoxCarNum.Text = "";
                textBoxCardNum.Text = "";
            }));
            yxYsTransportReturnDto = new Models.GetTruckYxInfoRceiveM();
            LedPageShow(Com.TipsStringHelper.Hyy);
            // });
        }

        private void InOut_Load(object sender, EventArgs e)
        {
            MyInit();
        }

        private void MyInit()
        {
            dLZCRunState = false;
            ShowDW = false;
            weightBZ = Convert.ToDouble(AppConfigHelper.GetAppSettings("weightBZ"));
            clearTextTime = Convert.ToInt32(AppConfigHelper.GetAppSettings("ClearTextTime"));
            poundHasData = false;
            nowWeight = 0;
            siloCoalName = AppConfigHelper.GetAppSettings("SiloCoalName");
            dlzcState = true;
            DelegateHelper.InfoMessageEvent += PageShow;
            DelegateHelper.CameraGetCarNumEvent += CameraGetCarNum;
            Common.DelegateHelper.WeightCallbackEvent += WeightCallback;
            InitCamera();
            InitLed();
            InitRead();
            InitTimer();
            InitDLZC();
            InitWagonBalance();

            yRTReaderBLL.getDataCallbackEvent = GetReadDataCallback;
            Common.DelegateHelper.SendWidthHeightEvent += SendWidthHeight;
        }
        private void SendWidthHeight(int Width, int height)
        {
            if (wFAutoSizeHelper.ControlsInfo.Count > 0)//如果字典中有数据，即窗体改变
            {
                wFAutoSizeHelper.ControlsChangeInit(Width, height);//表示pannel控件
                wFAutoSizeHelper.ControlsChange(this.Controls[0]);
            }
        }
        /// <summary>
        /// 初始化地磅
        /// </summary>
        private void InitWagonBalance()
        {
            toledoWagonBalanceBLL = new ToledoWagonBalanceTCBLL();
        }

        /// <summary>
        /// 地磅数据回调委托
        /// </summary>
        /// <param name="weight"></param>
        private void WeightCallback(double weight)
        {
            if (weight != -1)
            {
                nowWeight = weight;
                SetWeightDataInPage();
            }

            if (weight > weightBZ && dlzcState)
            {
                dlzcState = false;
            }


            //if (!string.IsNullOrWhiteSpace(textBoxCardNum.Text.Trim()) && (yxYsTransportReturnDto != null) && !string.IsNullOrWhiteSpace(yxYsTransportReturnDto.cardNo) && !dlzcState)
            //{
            //    decimal? yl = yxYsTransportReturnDto.ratedLoad - Convert.ToDecimal(weight);
            //    if (yl < 1)
            //    {
            //        dLZCBLL.RunClose();
            //        dlzcState = true;
            //        ClearText();
            //    }
            //}

            if (weight < weightBZ && !dlzcState)
            {
                ShowDWTimer.Stop();
                dlzcState = true;
                ClearText();
                if (dLZCRunState)
                {
                    dLZCRunState = false;
                    dLZCBLL.RunClose();

                }
            }

        }

        /// <summary>
        /// 将委托的数据赋值给页面
        /// </summary>
        public void SetWeightDataInPage()
        {
            this.Invoke(new Action(() =>
            {
                label4.Text = nowWeight.ToString();
            }));
        }

        private void InitDLZC()
        {
            dLZCBLL = new DLZCBLL();
        }

        private void InitTimer()
        {
            rePeatCardNumTimer.Elapsed += RePeatCardNumTimer_Elapsed;
            rePeatCardNumTimer.Enabled = true;
            rePeatCardNumTimer.AutoReset = false;
            rePeatCardNumTimer.Start();

            ShowDWTimer.Elapsed += ShowDWTimer_Elapsed;
            ShowDWTimer.Enabled = false;
            ShowDWTimer.AutoReset = true;

        }

        private void ShowDWTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            if (nowWeight > (weightBZ + FJDW))
            {
                LedShow("当前吨位：" + nowWeight + "吨");
            }
        }

        private void RePeatCardNumTimer_Elapsed(object sender, ElapsedEventArgs e)
        {

        }

        private void InitRead()
        {
            yRTReaderBLL = new HardWareBLL.YRTReaderBLL();

        }

        /// <summary>
        /// 读卡器数据的回调
        /// </summary>
        /// <param name="epc"></param>
        //private void GetReadDataCallback(string epc)
        //{
        //    lock (obj)
        //    {
        //        SetCardNum(epc);
        //        if (cardNumNow == epc)
        //        {
        //            if (rePeatCardNumTimer.Enabled)
        //            {
        //                PageShow("当前卡号重复，倒计时还在继续！");
        //            }
        //            else
        //            {
        //                DoSomthing();
        //            }

        //        }
        //        else
        //        {
        //            LedPageShow("当前卡号：" + epc);
        //            cardNumNow = epc;
        //            DoSomthing();
        //        }
        //    }
        //}
        private void GetReadDataCallback(string epc)
        {
            lock (obj)
            {
                string reaStr = epc.Substring(0, 12);
                SetCardNum(reaStr);
                if (cardNumNow == epc)
                {
                    if (rePeatCardNumTimer.Enabled)
                    {
                        PageShow("当前卡号重复，倒计时还在继续！");
                    }
                    else
                    {
                        if (epc.Length != 12)
                        {
                            LedPageShow(epc);
                            return;
                        }
                        DoSomthing();
                    }
                }
                else
                {
                    cardNumNow = epc;
                    if (epc.Length != 12)
                    {
                        LedPageShow(epc);
                        return;
                    }
                    LedPageShow("当前卡号：" + reaStr);
                    DoSomthing();
                }
            }
        }
        /// <summary>
        /// 抛出异常
        /// </summary>
        /// <param name="str"></param>
        void MessageThrow(string str)
        {
            throw new Exception(str);
        }

        /// <summary>
        /// 查询并判断流程
        /// </summary>
        void DoSomthing()
        {
            try
            {
                if (!rePeatCardNumTimer.Enabled)
                {
                    rePeatCardNumTimer.Start();
                }
                if (dLZCRunState)
                {
                    dLZCRunState = false;
                    dLZCBLL.RunClose();

                }

                string cardNum = textBoxCardNum.Text.Trim();
                string carNum = textBoxCarNum.Text.Trim();
                //if (!string.IsNullOrWhiteSpace(cardNum) && !string.IsNullOrWhiteSpace(carNum))
                //{
                Models.GetTruckYxInfoSendM getTruckYxInfoSendM = new Models.GetTruckYxInfoSendM()
                {
                    cardNo = cardNum,
                    truckNo = carNum
                };

                var resGetTruckYxInfo = AutoControlTransportApiServer.GetTruckYxInfo(getTruckYxInfoSendM);
                if (!resGetTruckYxInfo.success)
                {
                    MessageThrow(resGetTruckYxInfo.msg);
                }

                if (resGetTruckYxInfo.data == null || string.IsNullOrWhiteSpace(resGetTruckYxInfo.data.cardNo))
                {
                    MessageThrow(resGetTruckYxInfo.msg);
                }
                yxYsTransportReturnDto = resGetTruckYxInfo.data == null ? new Models.GetTruckYxInfoRceiveM() : resGetTruckYxInfo.data;
                SetText();
                if (siloCoalName != yxYsTransportReturnDto.coalName)
                {
                    MessageThrow("煤种不匹配，请到 " + yxYsTransportReturnDto.coalName + " 仓装煤！");
                }

                //获取监控的图片
                List<string> picCodeList = new List<string>();
                string picG1 = cameraG.UpLoadFile();
                if (!string.IsNullOrWhiteSpace(picG1))
                {
                    picCodeList.Add(picG1);
                }
                string imgs1 = string.Join(",", picCodeList);

                //装车接口
                Models.TruckLoadingSendM admissionDtoSendM = new Models.TruckLoadingSendM()
                {
                    cardNo = cardNum,
                    truckNo = carNum,
                    imgs1 = imgs1
                };
                // Common.Log4.LogManage.WriteInfo("筒仓装车接口数据：" + Newtonsoft.Json.JsonConvert.SerializeObject(admissionDtoSendM));
                var resM = AutoControlTransportApiServer.TruckLoading(admissionDtoSendM);
                if (!resM.success)
                {
                    MessageThrow(resM.msg);
                }
                if (!dLZCRunState)
                {
                    dLZCRunState = true;
                    dLZCBLL.RunOpen();
                }
                // poundHasData = true;
                LedPageShow("正在装车，请稍等。。。");
                ShowDWTimer.Start();
                //}
            }
            catch (Exception ex)
            {
                LedPageShowLog(ex);
            }
        }
        /// <summary>
        /// 将异常信息显示的led page上， 并记录错误日志。
        /// </summary>
        /// <param name="str"></param>
        private void LedPageShowLog(Exception ex)
        {
            LedShow(ex.Message);
            PageShow(ex.Message);
            Common.Log4.LogManage.WriteErr(ex.ToString());
        }
        /// <summary>
        /// 在页面设置卡号
        /// </summary>
        void SetCardNum(string str)
        {
            this.Invoke(new Action(() =>
            {
                textBoxCardNum.Text = str;
            }));
        }

        private void CameraGetCarNum(string carNum, string cameraIp)
        {
            //throw new NotImplementedException();
            Common.Log4.LogManage.WriteInfo("称重页面拿到了车牌:" + carNum + " 摄像头ip：" + cameraIp);
            SetCarNumInPage(carNum);
            LedPageShow("当前车牌：" + carNum);
            //DoSomthing();

        }

        void SetCarNumInPage(string carNum)
        {
            this.Invoke(new Action(() =>
            {
                textBoxCarNum.Text = carNum;
            }));
        }

        private void InitCamera()
        {
            //Q
            {
                Common.HaredWareCommonM cameraScalesQ = Common.IConfig.GetSetCameraScalesQ;
                Common.CameraModel cameraModelQ = new Common.CameraModel()
                {
                    Name = cameraScalesQ.Name,
                    Ip = cameraScalesQ.Ip,
                    Port = Convert.ToInt32(cameraScalesQ.Port),
                    PassWord = cameraScalesQ.PassWord,
                    UserName = cameraScalesQ.UserName
                };
                PageShow("cameraModelQ 初始化");
                cameraQ = new CameraBLL(cameraModelQ);
                cameraQ.ManualOne(pictureBoxQ);
            }

            //G
            {
                Common.HaredWareCommonM cameraScalesG = Common.IConfig.GetSetCameraScalesG1;
                Common.CameraModel cameraModelG = new Common.CameraModel()
                {
                    Ip = cameraScalesG.Ip,
                    Name = cameraScalesG.Name,
                    Port = Convert.ToInt32(cameraScalesG.Port),
                    PassWord = cameraScalesG.PassWord,
                    UserName = cameraScalesG.UserName
                };
                PageShow("cameraModelG1 初始化");
                cameraG = new CameraBLL(cameraModelG);
                cameraG.ManualOne(pictureBoxG);
            }
        }

        /// <summary>
        /// 手动放煤按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                var userM = IConfig.GetSetuserInfo;
                string passWord = Interaction.InputBox("密码", "请输入密码");
                if (string.IsNullOrWhiteSpace(passWord))
                {
                    MessageBox.Show("密码不能为空！");
                    return;
                }
                if (userM.PassWord != passWord)
                {
                    MessageBox.Show("密码错误，请重试！");
                    return;
                }
                else
                {

                    //授权卸煤
                    if (!dLZCRunState)
                    {
                        dLZCRunState = true;
                        dLZCBLL.RunOpen();
                        Common.Log4.LogManage.WriteWarn(userM.LoginAccount + "在" + DateTime.Now.ToString() + "开启了" + AppConfigHelper.GetAppSettings("SiloNum") + "筒仓的手动卸煤权限。");
                        MessageBox.Show("授权成功，请卸煤,卸煤完成后及时关闭");
                    }

                }
            }
            catch (Exception ex)
            {
                Common.Log4.LogManage.WriteErr(ex.ToString());
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        ///卸煤操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                var userM = IConfig.GetSetuserInfo;
                if (dLZCRunState)
                {
                    dLZCRunState = false;
                    dLZCBLL.RunClose();
                    Common.Log4.LogManage.WriteWarn(userM.LoginAccount + "在" + DateTime.Now.ToString() + "关闭了" + AppConfigHelper.GetAppSettings("SiloNum") + "筒仓的手动卸煤权限。");
                    MessageBox.Show("成功关闭卸煤！");
                }
            }
            catch (Exception ex)
            {
                Common.Log4.LogManage.WriteErr(ex.ToString());
                MessageBox.Show(ex.Message);
            }
        }
    }
}
